package frame.system.mapper;

import frame.system.qo.AuthQo;
import frame.system.to.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 *
 * @author
 * @since
 */
@Repository
public interface UserMapper extends Mapper<User> {

    // 字段
    String FIELDS = "t.full_name,t.nike_name,t.username,t.password,t.salt,t.session_id,t.host,t.login_times,t.error_times,t.error_continues,t.locked,t.lock_reason,t.dept_id,t.description,t.valid,t.create_time,t.update_time,t.id";
    // 表名 as 别名
    String TABLE = "sys_user t";
    // mapper包名
    String PACKAGE = "frame.system.mapper";

    @Results({
        @Result(column = "id", property = "id",id = true),
        @Result(column = "dept_id",property = "deptId"),
        @Result(column = "dept_id", property = "dept", one = @One(select = PACKAGE + ".DeptMapper.selectByPrimaryKey")),
        @Result(column = "id", property = "roles", many = @Many(select = PACKAGE + ".RoleMapper.allListByUserId"))
    })
    @Select({"<script>SELECT ", FIELDS," FROM ", TABLE,
            " WHERE t.valid=#{valid}",
            "<when test='username!=null'> AND username LIKE CONCAT('%',#{username},'%')</when>",
            "<when test='fullName!=null'> AND full_name LIKE CONCAT('%',#{fullName},'%')</when>",
            "<when test='deptId!=null'> AND dept_id=#{deptId}</when>",
            "ORDER BY ${orderStr}",
            "</script>"})
    List<User> pageList(AuthQo qo);


    // 用户登陆查询
    @Select({"SELECT " + FIELDS  + " FROM ", TABLE, " WHERE t.username = #{0} AND valid = 1"})
    User getByUsername(String username);

    @Select({"<script>","SELECT count(id) FROM ", TABLE,
            " WHERE username = #{username} AND valid = 1",
            "<when test='id!=null' > AND id !=#{id}</when>","</script>"})
    int countByUsername(AuthQo qo);

    @Insert({"<script>",
            "INSERT INTO sys_user_2_role VALUES ",
            "<foreach collection='rids' item='rid' index='index' separator=','>",
                "(#{uid},#{rid})",
            "</foreach>",
            "</script>"})
    int addRoles(@Param("uid") Integer userId, @Param("rids") List<Integer> roleIds);

    @Delete("DELETE FROM sys_user_2_role WHERE uid = #{0}")
    int deleteRoles(Integer userId);

    @Select({"SELECT count(*) FROM ", TABLE, " WHERE t.dept_id = #{0} AND valid = 1"})
    long countByDeptId(Integer deptId);

    // 将部门重置为1
    @Update("UPDATE " + TABLE +" SET dept_id=1 WHERE t.dept_id = #{0}")
    int updateDeptToDefault(Integer deptId);
    // 用户级联查询
    @Select({"SELECT t.full_name,t.nike_name,t.username,t.id FROM ", TABLE, " WHERE t.id = #{0} AND valid = 1"})
    User cascadeById(Integer uid);
    // 用户级联查询
    @Select({"SELECT t.full_name,t.nike_name,t.username,t.id FROM ", TABLE, " WHERE t.username = #{0} AND valid = 1"})
    User cascadeByUsername(String username);

}
